package cn.junechiu.mytodo

import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import butterknife.BindView
import butterknife.ButterKnife
import cn.junechiu.mytodo.TodoApp.Companion.MY_TAG
import io.realm.Realm

/**
 * Created by android on 2017/11/2.
 */
class TodosFragment : Fragment(), TodoAdapter.ItemClickListener {

    @BindView(R.id.todos_recycler_view)
    lateinit var recyclerView: RecyclerView

    private var realm: Realm? = null

    companion object {
        fun newInstance(): TodosFragment {
            return TodosFragment()
        }
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val v = inflater!!.inflate(R.layout.fragment_todos, container, false)
        ButterKnife.bind(this, v)
        return v
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        realm = Realm.getDefaultInstance()
    }

    override fun onResume() {
        super.onResume()
        val todos = realm!!.where(Todo::class.java).findAll()
        Log.i(MY_TAG, "onResume: ${todos}")
        Log.i(MY_TAG, "onResume: recyclerView = ${recyclerView} ")
        val adapter = TodoAdapter(activity, todos, this)
        recyclerView.layoutManager = LinearLayoutManager(activity)
        recyclerView.setAdapter(adapter)
        adapter.notifyDataSetChanged()
    }

    // 点击事项，跳转编辑 EditFragment
    override fun onClick(caller: View, todo: Todo) {
        (activity as MainActivity).hideFab()
        val todoEditFragment = TodoEditFragment.newInstance(todo.id)
        activity.supportFragmentManager
                .beginTransaction()
                .replace(R.id.content_main, todoEditFragment, todoEditFragment.javaClass.getSimpleName())
                .addToBackStack(todoEditFragment.javaClass.getSimpleName())
                .commit()
    }

    override fun onDestroy() {
        super.onDestroy()
        realm!!.close()
    }
}